import axios from 'axios'
import qs from 'qs'
import { getToken } from '../utils/auth'
import setting from '../settings'
import ajax from '../utils/request'

const authPath = 'auth'

const loginAjax = axios.create({
  baseURL: setting.authUrl,
  timeout: 60000,
  auth: { username: setting.clientId, password: setting.clientSecret },
  headers: {
    'content-type': 'application/x-www-form-urlencoded'
  }
})

const logout = (userSession) => {
  return axios.create({
    baseURL: setting.authUrl,
    timeout: 5000,
    headers: {
      Authorization: userSession ? `Bearer ${userSession}` : ''
    }
  })
}

export const loginApi = (params) => {
  return loginAjax.post('oauth/token', qs.stringify(params))
}
export const logoutApi = (params) => {
  const userSession = getToken()
  return logout(userSession).get('oauth/remove_token')
}

export const userProfileApi = (params) => {
  return ajax.get(`${authPath}/user/profile`, { baseURL: setting.authUrl })
}

export const userMenuApi = (params) => {
  return ajax.get(`${authPath}/user/sysMenu`, {
    baseURL: setting.authUrl,
    params,
    paramsSerializer: (params) => {
      return qs.stringify(params, { arrayFormat: 'repeat' })
    }
  })
}

export const userSettingApi = (params) => {
  return ajax.get(`${authPath}/user/setting`, { params })
}

export const updatePwdApi = (params) => {
  return ajax.put(`${authPath}/profile/passwd?` + qs.stringify(params), {}, { baseURL: setting.authUrl })
}

export const updateUserProfileApi = (params) => {
  return ajax.put(`${authPath}/profile`, params, { baseURL: setting.authUrl })
}
